import type { jsonSchema } from '@/store'

export const createId = () => Math.floor(Math.random() * 100000).toString(16)

export function getAttributeNode(ele: HTMLElement | null,
  attribute: string): HTMLElement | null {
  if (!ele)
    return null
  while (
    ele!.getAttribute
    && !ele!.getAttribute(attribute)
    && ele !== document.body
  )

    ele = ele!.parentNode as any

  if (ele === document.body)
    return null

  return ele
}

export const searchId: any = (data: typeof jsonSchema.value['componentsTree'], id: string) => {
  const stack = [...data]
  while (stack.length > 0) {
    const obj = stack.pop() as any
    if (obj && obj.componentid === id)
      return obj

    if (obj && obj.children)
      stack.push(...obj.children)

    if (obj && typeof obj === 'object') {
      for (const prop in obj) {
        if (Array.isArray(obj[prop]))
          stack.push(...obj[prop])
        else if (typeof obj[prop] === 'object')
          stack.push(obj[prop])
      }
    }
  }
  return undefined
}

interface Component {
  componentid: string
  $componentName: string
  fileName: string
  hasSlot: boolean
  children?: Component[]
  props?: Record<string, any>
}

export function getComponentPath(
  components: Component[],
  componentid: string,
  path = '',
): string | null {
  for (let i = 0; i < components.length; i++) {
    const component = components[i]
    if (component.componentid === componentid) {
      return `${path}[${i}]${
        component.$componentName.startsWith('$') ? component.$componentName.slice(1) : component.$componentName
      }`
    }
    else if (component.children) {
      const result = getComponentPath(component.children, componentid, `${path}[${i}]`)
      if (result)
        return result
    }
  }
  return null
}
